package com.codeczx.mygeeknews;

import com.codeczx.mygeeknews.zhihu.ZhiHuApis;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class Api {

    public ZhiHuApis service;

    private static class SingletonHolder{
        private static final Api INSATANCE = new Api();
    }

    public static Api getInstance(){
        return SingletonHolder.INSATANCE;
    }

    private Api() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        File cacheFile = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (SystemUtils.isNetworkConnected()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if (SystemUtils.isNetworkConnected()) {
                    // 有网络时，不做缓存，最大保存时长为0
                    int maxAge = 0;
                    response = response.newBuilder()
                            .addHeader("Cache-Control", "public,max-age="+maxAge)
                            // Pragma:no-cache会导致文件无法被缓存
                            .removeHeader("Pragma")
                            .build();
                }else{
                    // 无网络时，缓存时间设置为4周
                    int maxStale = 60 * 60 * 24 * 4;
                    response = response.newBuilder()
                            .addHeader("Cache-Control","public,only-if-cached,max-stale="+maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
        builder.addNetworkInterceptor(interceptor);
        builder.cache(cache);
        builder.connectTimeout(20, TimeUnit.SECONDS);
        builder.readTimeout(10,TimeUnit.SECONDS);
        builder.writeTimeout(10,TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ZhiHuApis.HOST)
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        service = retrofit.create(ZhiHuApis.class);
    }

}
